using System.Collections.Generic;
using UnityEngine;

namespace NodeCanvas.BehaviourTrees
{
	[AddComponentMenu("")]
	[Name("Parallel")]
	[Category("Composites")]
	[Description("Execute all child nodes once but simultaneously and return Success or Failure depending on the selected Policy.\nIf is Dynamic higher priority chilren status are revaluated")]
	[Icon("Parallel")]
	public class BTParallel : BTComposite
	{
		public enum Policy
		{
			FirstFailure = 0,
			FirstSuccess = 1
		}

		public Policy policy;

		public bool isDynamic;

		private List<Connection> finishedConnections = new List<Connection>();

		public override string nodeName
		{
			get
			{
				return string.Format("<color=#ff64cb>{0}</color>", base.nodeName.ToUpper());
			}
		}

		protected override Status OnExecute(Component agent, Blackboard blackboard)
		{
			for (int i = 0; i < base.outConnections.Count; i++)
			{
				if (isDynamic || !finishedConnections.Contains(base.outConnections[i]))
				{
					base.status = base.outConnections[i].Execute(agent, blackboard);
					if (base.status == Status.Failure && policy == Policy.FirstFailure)
					{
						ResetRunning();
						return Status.Failure;
					}
					if (base.status == Status.Success && policy == Policy.FirstSuccess)
					{
						ResetRunning();
						return Status.Success;
					}
					if (base.status != Status.Running && !finishedConnections.Contains(base.outConnections[i]))
					{
						finishedConnections.Add(base.outConnections[i]);
					}
				}
			}
			if (finishedConnections.Count == base.outConnections.Count)
			{
				if (policy == Policy.FirstFailure)
				{
					return Status.Success;
				}
				if (policy == Policy.FirstSuccess)
				{
					return Status.Failure;
				}
			}
			return Status.Running;
		}

		protected override void OnReset()
		{
			finishedConnections.Clear();
		}

		private void ResetRunning()
		{
			for (int i = 0; i < base.outConnections.Count; i++)
			{
				if (base.outConnections[i].connectionStatus == Status.Running)
				{
					base.outConnections[i].ResetConnection();
				}
			}
		}
	}
}
